/**
 * 
 */
package com.zqp.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zqp.dto.FileInfo;

/**
* @author zqp
* @date 2017年12月19日 
* @description 
*/
@RestController
@RequestMapping("/file")
public class FileController {
	String folder="D:\\gitspace\\spring-security-practice\\zqp-security-demo\\src\\main\\java\\com\\zqp\\web\\controller";
	@PostMapping
	public FileInfo upload(MultipartFile file) throws IllegalStateException, IOException {
	
		System.out.println(file.getName());
		System.out.println(file.getOriginalFilename());
		System.out.println(file.getSize());
		
		File localFile = new File(folder,new Date().getTime()+".txt");
		
		file.transferTo(localFile);
		return new FileInfo(localFile.getAbsolutePath());
		
	}
	@GetMapping("/{id}")
	public  void download(@PathVariable String id,HttpServletResponse response,HttpServletRequest request) throws Exception {
		try (
				//jdk7  在try 括号 里  流会自动关闭
			InputStream in = new FileInputStream(new File(folder,id+".txt"));
			OutputStream out = response.getOutputStream();){
			response.setContentType("appliction/x-download");
			response.addHeader("Content-Disposition", "attachment;filename=test.txt");
			IOUtils.copy(in, out);//输入流 ->输出流
			out.flush();
		}
		
	}
	
}
